 <?php
 class Extension_Catalog_Block_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
 {



    public function getAvailableOrders()
    {
        //return $this->_availableOrder;
        //Custom Order list Edit
        $this->_availableOrder = array(
                                  
            'qty_ordered' => $this->__('Best Sellers'),
            'mostviewd'=> $this->__('Most Viewed'),
            'entity_id' => $this->__('Newly Added'),
            //'position'      => $this->__('Position'), 
            //'name' => $this->__('Name'),
            'price' => $this->__('Highest Price')
             
                
            
        );
        $this->setDefaultOrder('Name');
		
        //Custom Available Order -Edit finish
        return $this->_availableOrder;
    }
    
   
   /**
     * Retrieve available Order fields list
     *
     * @return array
     */
 

	
    public function setCollection($collection)
    {
        $this->_collection = $collection;
	
        $this->_collection->setCurPage($this->getCurrentPage());

        // we need to set pagination only if passed value integer and more that 0
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }
        if ($this->getCurrentOrder()) {
            $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
        }
        if($this->getCurrentOrder()=='mostviewd') 
        {
		$this->_collection->getSelect()->
                 joinInner('report_event AS _table_views',
                         
                       ' _table_views.object_id = e.entity_id',
                         'COUNT(_table_views.event_id) AS views')->
                 group('e.entity_id')->order('views DESC');
	}
		
	$sql = $this->_collection->getSelectSql(true);
        
          
       $limit= $this->getDefaultPerPageValue();
       $page =  $this->getRequest()->getParam('p');


       if(isset($page))
       {
           if(($page - 1) == 0)
           {
               $this->_collection->getSelect()->limit($limit);
           }
           else
           {
               $this->_collection->getSelect()->limit($limit, ($page-1) * $limit);
           }
       }
       else
       {
           $this->_collection->getSelect()->limit($limit);
       }

        $this->_collection->getSelect()->limit($limit);   
        $this->_collection->load();	   
		   
//		$this->_collection->printlogquery(true); exit;
        return $this;
    }	
	
}